#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t mutex;

int *tfn(void *args){
    srand(time(NULL));
    int ret;
    while(1){
        ret = pthread_mutex_lock(&mutex);
        if (ret != 0){
            fprintf(stderr,"sub mutex lock  error %s\n",strerror(ret));
            exit(1);
        }
        printf("hello ");
        sleep(rand() % 3);
        printf("world\n");
        ret = pthread_mutex_unlock(&mutex);
        if (ret != 0){
            fprintf(stderr,"sub mutex unlock error %s\n",strerror(ret));
            exit(1);
        }
        sleep(rand() % 3);
    }
    return 0;
}

int main(){
    pthread_t tid;
    srand(time(NULL));
    int ret = pthread_mutex_init(&mutex,NULL);
    if (ret != 0){
        fprintf(stderr," main mutex init error %s\n",strerror(ret));
        exit(1);
    }
    pthread_create(&tid,NULL,(void*)tfn,NULL);
    while(1){
        ret = pthread_mutex_lock(&mutex);
        if (ret != 0){
            fprintf(stderr," main mutex lock error %s\n",strerror(ret));
            exit(1);
        }
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        ret = pthread_mutex_unlock(&mutex);
        if (ret != 0){
            fprintf(stderr,"main mutex unlock error %s\n",strerror(ret));
            exit(1);
        }
        sleep(rand() % 3);
    }
    ret = pthread_join(tid,NULL);
    if (ret != 0){
        fprintf(stderr,"pthread_join error %s\n",strerror(ret));
        exit(1);
    }
    return 0;
    ret = pthread_mutex_destroy(&mutex);
    if (ret != 0){
        fprintf(stderr,"mutex destroy error %s\n",strerror(ret));
        exit(1);
    }
    return 0;
}